<template>
  <view class="h-screen flex flex-col bg-[#fbfcfd]">
    <!-- 顶部导航栏 -->
    <view
      class="relative z-10 h-90rpx flex flex-shrink-0 items-center justify-between border-b-1 border-b-[#eee] bg-white pt-60rpx"
    >
      <view class="ml-20rpx h-60rpx w-60rpx flex items-center justify-center" @tap="goBack">
        <image src="https://ceshiweb.picaime.com/static/images/cart/back.png" class="h-36rpx w-36rpx" mode="aspectFit" />
      </view>
      <view class="pointer-events-none absolute left-0 right-0 flex items-center justify-center">
        <text class="text-36rpx text-black font-bold leading-[49.4rpx] tracking-0">
          购物车
        </text>
      </view>
      <view class="mr-20rpx flex items-center justify-center" @tap="onGetOrder">
        <view class="h-52rpx w-146rpx flex items-center justify-center rounded-6rpx bg-[#43CF7C]">
          <text class="text-30rpx text-white">
            取单
          </text>
          <view class="ml-10rpx h-40rpx w-40rpx flex items-center justify-center rounded-50% bg-[#EB0E0E] font-bold">
            <text class="text-24rpx text-white">
              {{ orderCount }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分隔线 -->
    <view class="h-2rpx flex-shrink-0 bg-[rgba(245,245,245,1)]" />

    <!-- 买家选择区域 -->
    <view class="flex flex-shrink-0 items-center justify-between bg-white px-30rpx">
      <view class="w-500rpx flex flex-1 items-center">
        <scroll-view scroll-x class="h-110rpx whitespace-nowrap" style="line-height: 110rpx;">
          <view
            v-for="(buyer, index) in buyerList" :key="index" class="relative mr-20rpx inline-block"
            @tap="selectBuyer(index)"
          >
            <view
              class="h-66rpx flex items-center justify-center rounded-12rpx px-16rpx" :class="[
                selectedBuyerIndex === index
                  ? 'bg-[#43CF7C] text-white'
                  : 'bg-[#f0f0f0] text-[#333] border-1 border-[#e0e0e0]',
              ]"
            >
              <text class="text-28rpx">
                {{ buyer.name }}{{ buyer.sort ? `(${buyer.sort})` : '' }}
              </text>
            </view>
            <view
              v-if="buyer.car_num && buyer.car_num > 0"
              class="absolute right-0 top-0 h-32rpx w-32rpx flex translate-x-1/2 items-center justify-center rounded-50% bg-[#EB0E0E] -translate-y-1/2"
            >
              <text class="text-18rpx text-white">
                {{ buyer.car_num }}
              </text>
            </view>
            <view
              v-if="selectedBuyerIndex === index"
              class="absolute left-0 right-0 top-58rpx z-10 flex justify-center"
            >
              <view
                class="h-0 w-0"
                style="border-left: 15rpx solid transparent; border-right: 15rpx solid transparent; border-top: 15rpx solid #43CF7C;"
              />
            </view>
          </view>
        </scroll-view>
      </view>
      <view
        class="mt-5rpx h-60rpx w-100rpx flex items-center justify-center border-1 border-[#43CF7C] rounded-8rpx"
        @tap="onAdd"
      >
        <img src="https://ceshiweb.picaime.com/static/images/cart/addMore.png" alt="" class="h-60rpx w-60rpx">
      </view>
    </view>

    <!-- 商品列表区域 -->
    <view class="flex-1">
      <view class="mb-20rpx rounded-16rpx">
        <!-- 表头 -->
        <view class="h-60rpx w-full flex items-center rounded-t-16rpx bg-[rgba(245,246,249,0.9)] px-20rpx">
          <text class="w-180rpx text-center text-28rpx text-black font-normal leading-44rpx tracking-0">
            货品信息
          </text>
          <text class="w-150rpx text-center text-28rpx text-black font-normal leading-44rpx tracking-0">
            数量
          </text>
          <text class="w-150rpx text-center text-28rpx text-black font-normal leading-44rpx tracking-0">
            单价
          </text>
          <text class="w-150rpx text-center text-28rpx text-black font-normal leading-44rpx tracking-0">
            货款
          </text>
          <text
            class="w-70rpx text-center text-28rpx text-[#EB0E0E] font-normal leading-44rpx tracking-0"
            @tap="clearAllItems"
          >
            清空
          </text>
        </view>

        <!-- 商品项 -->
        <view
          v-for="(item, index) in goodsList" :key="index" :class="{
            'bg-[rgba(230,242,235,0.38)]': item.selected,
            'bg-white': !item.selected,
            'mt-15rpx': index > 0,
          }" class="flex flex-col border-b-1 border-b-[#eee]" @tap="toggleSelectItem(index)"
        >
          <view class="flex items-center px-20rpx py-10rpx">
            <!-- 货品信息列 -->
            <view class="relative w-180rpx">
              <view class="flex-col" :class="item.metadata.pici_info ? 'ml-2' : 'ml-4'">
                <text class="text-28rpx text-black font-bold tracking-1rpx">
                  {{ item.name }}
                </text>
                <view class="mt-8rpx">
                  <text
                    v-if="item.metadata.pici_info"
                    class="mr-10rpx inline-block rounded-4rpx bg-[#EB0E0E] px-8rpx py-2rpx text-22rpx text-white"
                  >
                    {{ item.metadata.pici_info?.huozhu?.lxr_name }} / {{ item.metadata.pici_id }}
                  </text>
                </view>
              </view>
              <text class="absolute bottom-0 left-[-20rpx] text-32rpx text-black font-bold">
                {{ index + 1 }}.
              </text>
            </view>

            <!-- 数量列 -->
            <view class="w-150rpx flex items-center justify-center">
              <text class="text-26rpx text-[#EB0E0E]">
                {{ item.quantity }}{{ item.unit }}
              </text>
            </view>

            <!-- 单价列 -->
            <view class="w-150rpx flex items-center justify-center">
              <text class="text-26rpx text-[#333]">
                {{ item.price }}/{{ item.unit }}
              </text>
            </view>

            <!-- 货款列 -->
            <view class="w-150rpx flex items-center justify-center">
              <text class="text-26rpx text-[#333]">
                {{ item.money }}元
              </text>
            </view>

            <!-- 清空/删除列 -->
            <view class="w-70rpx flex items-center justify-center" @tap.stop="removeItem(index)">
              <image src="https://ceshiweb.picaime.com/static/images/delete.png" mode="widthFix" class="h-36rpx w-36rpx" />
            </view>
          </view>

          <!-- 标签和小计行 -->
          <view class="mt-4rpx flex items-center border-t-1 border-t-[#eee] px-20rpx py-12rpx">
            <view class="flex-1">
              <view v-for="(specItem, specIndex) in item.spec" :key="specIndex" class="mb-4rpx">
                <text
                  class="inline-block rounded-4rpx px-8rpx py-2rpx text-20rpx text-[#09D65B]"
                  style="border: 1px solid rgba(9, 214, 91, 1); border-radius: 2px;"
                >
                  {{ specItem }}
                </text>
              </view>
            </view>
            <view class="flex-1 text-center">
              <text class="text-22rpx text-[#333]">
                {{ formatFujiafei(item.fujiafei_list) }}
              </text>
            </view>
            <view class="flex-1 text-right">
              <text class="text-26rpx text-[#333]">
                小计：{{ item.subtotal }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view
      class="flex flex-shrink-0 items-center border-t-1 border-t-[#d1d1d1] bg-white p-20rpx"
      style="border-top-style: solid"
    >
      <view
        class="mr-20rpx h-92rpx w-156rpx flex items-center justify-center rounded-12rpx bg-[rgba(230,242,235,0.38)] text-[#333]"
        @tap="hangOrder"
      >
        <text class="text-38rpx text-[rgba(56,56,56,1)] font-bold leading-[52rpx] tracking-0">
          挂单
        </text>
      </view>
      <view
        class="mr-20rpx h-92rpx w-186rpx flex items-center justify-center rounded-16rpx bg-[rgba(245,250,247,1)] text-[#333]"
        @tap="batchOrder"
      >
        <text class="text-38rpx text-[rgba(56,56,56,1)] font-bold leading-[52rpx] tracking-0">
          批量下单
        </text>
      </view>
      <view
        class="h-114rpx w-372rpx flex flex-col justify-center rounded-16rpx bg-[rgba(17,237,105,1)] text-center"
        @tap="checkout"
      >
        <text class="text-38rpx text-black font-bold leading-[52rpx] tracking-0">
          结算收银
        </text>
        <text class="mt-10rpx text-36rpx text-white">
          合计：{{ totalAmount }}元
        </text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { dataCar, deleteCar, getMaijiaCar, guadanData } from '@/api/order/index';

// 类型定义
interface FujiafeiList {
  lizi?: number;
  kaipiao?: number;
  [key: string]: number | undefined;
}

interface Buyer {
  id: number;
  name: string;
  maijia_id: number;
  admin_id?: number;
  guadan?: string | null;
  time?: string;
  shouyin_id?: number;
  car_num?: number;
  order_id?: number | null;
  type?: number;
  sort?: number | null;
  maijia?: {
    id: number;
    username: string;
  };
}

interface GoodsItem {
  id: number;
  name: string;
  spec: string[];
  fujiafei_list: FujiafeiList;
  quantity: string;
  price: string;
  money: string;
  subtotal: string;
  selected: boolean;
  unit?: string;
  metadata?: any;
}

// 状态管理
const orderCount = ref<number>(5);
const buyerList = ref<Buyer[]>([]);
const selectedBuyerIndex = ref(0);
const goodsList = ref<GoodsItem[]>([]);

// 计算属性
const totalAmount = computed(() => {
  let total = 0;
  goodsList.value.forEach((item) => {
    total += Number.parseFloat(item.subtotal) || 0;
  });
  return total.toFixed(2);
});

// 方法定义
// 切换商品选中状态
const toggleSelectItem = (index: number) => {
  if (goodsList.value[index]) {
    goodsList.value[index].selected = !goodsList.value[index].selected;
  }
};

// 获取买家列表
const getMaiJiaList = async (people_id?: number) => {
  try {
    const res = await getMaijiaCar();
    if (res.code === 200 && res.data) {
      // 更新取单数量
      orderCount.value = res.data.qudanNum || 0;

      // 更新买家列表
      if (res.data.data && Array.isArray(res.data.data)) {
        buyerList.value = res.data.data;

        if (people_id) {
          handleGoodFromPick(people_id, buyerList.value);
        }
        else {
          selectedBuyerIndex.value = 0;
          await selectBuyer(0);
        }
      }
    }
  }
  catch (error) {
    console.error('获取买家列表失败', error);
  }
};

// 更新买家列表处理函数
const handleUpdateBuyer = async (buyer: Buyer) => {
  // 调用getMaiJiaList刷新整个买家列表
  await getMaiJiaList();

  // 找到新添加的买家索引并选中它
  const newBuyerIndex = buyerList.value.findIndex(item => item.maijia_id === buyer.maijia_id);
  if (newBuyerIndex >= 0) {
    // 选中该买家
    selectBuyer(newBuyerIndex);
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取订单
const onGetOrder = () => {
  uni.navigateTo({
    url: '/pages/tab/pick/index',
  });
};

// 添加从取单页面返回后的处理函数
const handleGoodFromPick = (id: number, list: Buyer[]) => {
  const matchIndex = list.findIndex(buyer => buyer.id == id);
  if (matchIndex !== -1) {
    selectBuyer(matchIndex);
  }
};

// 跳转到选择买家页面
const onAdd = () => {
  // 获取当前选中的买家
  const selectedBuyer = buyerList.value[selectedBuyerIndex.value];
  const car_id = selectedBuyer?.id || 0;

  uni.navigateTo({
    url: `/pages/common/selectBuyer/index?car_id=${car_id}`,
  });
};

// 删除购物车商品项
const removeItem = async (index: number) => {
  // 显示确认对话框
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const selectedBuyer = buyerList.value[selectedBuyerIndex.value];
          const item = goodsList.value[index];

          // 调用deleteCar接口删除商品
          const res = await deleteCar({
            car_id: selectedBuyer.id,
            order_car_id: item.id,
          });

          if (res.code === 200) {
            // 删除成功，从本地列表中移除
            goodsList.value.splice(index, 1);
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            });
          }
          else {
            uni.showToast({
              title: res.msg || '删除失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          console.error('删除商品失败', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 挂单功能
const hangOrder = async () => {
  try {
    // 获取当前选中买家信息
    const selectedBuyer = buyerList.value[selectedBuyerIndex.value];

    if (!selectedBuyer) {
      uni.showToast({
        title: '请先选择买家',
        icon: 'none',
      });
      return;
    }

    // 调用挂单API
    const res = await guadanData({
      car_id: selectedBuyer.id,
    });

    if (res.code === 200) {
      uni.showToast({
        title: '挂单成功',
        icon: 'success',
      });

      // 刷新买家列表和商品列表
      await getMaiJiaList();
    }
    else {
      uni.showToast({
        title: res.msg || '挂单失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('挂单失败', error);
    uni.showToast({
      title: '挂单失败',
      icon: 'none',
    });
  }
};

// 批量下单功能
const batchOrder = () => {
  // 实现批量下单功能
};

// 结算功能
const checkout = () => {
  // 获取当前选中的买家
  const selectedBuyer = buyerList.value[selectedBuyerIndex.value];

  if (!selectedBuyer) {
    uni.showToast({
      title: '请先选择买家',
      icon: 'none',
    });
    return;
  }

  if (goodsList.value.length === 0) {
    uni.showToast({
      title: '购物车为空',
      icon: 'none',
    });
    return;
  }

  const settlementData = {
    orderId: selectedBuyer.id,
    buyerName: selectedBuyer.maijia?.username || '临时客户',
    buyerPhone: '',
    orderItems: goodsList.value.map(item => item.metadata),
    yingshou: Number.parseFloat(totalAmount.value),
    heji: Number.parseFloat(totalAmount.value),
    shishou: Number.parseFloat(totalAmount.value),
    cash_num: Number.parseFloat(totalAmount.value),
    wepay_num: 0,
    alipay_num: 0,
    union_num: 0,
    other_num: 0,
    car_id: selectedBuyer.id,
    maijia_id: selectedBuyer.maijia_id,
  };

  // 将数据保存到本地存储
  uni.setStorageSync('settlementData', settlementData);

  // 跳转到收银台页面
  uni.navigateTo({
    url: '/pages/common/settlement/index',
  });
};

// 格式化附加费显示
const formatFujiafei = (fujiafei: FujiafeiList) => {
  const result: string[] = [];

  // 遍历附加费对象
  Object.entries(fujiafei).forEach(([key, value]) => {
    if (value && value > 0) {
      result.push(`${key}${value}`);
    }
  });

  return result.join(' ');
};

// 选择买家的方法
const selectBuyer = async (index: number) => {
  selectedBuyerIndex.value = index;

  const selectedBuyer = buyerList.value[index];
  if (selectedBuyer) {
    try {
      // 调用dataCar API，传递car_id和maijia_id参数
      const res = await dataCar({
        car_id: selectedBuyer.id,
        maijia_id: selectedBuyer.maijia_id,
      });

      // 处理返回的数据并更新商品列表
      if (res.code === 200 && res.data && res.data.data) {
        // 清空现有商品列表
        goodsList.value = [];

        // 遍历返回的商品数据并添加到商品列表
        res.data.data.forEach((item: any) => {
          // 处理附加费
          const fujiafeiList: FujiafeiList = {};

          // 优先使用goods_fujiafei
          if (item.goods_fujiafei && item.goods_fujiafei.length > 0) {
            item.goods_fujiafei.forEach((fee: any) => {
              if (Number.parseFloat(fee.total) > 0) {
                fujiafeiList[fee.name] = Number.parseFloat(fee.total);
              }
            });
          }
          // 备选使用extend.goods_fujiafei
          else if (item.extend && item.extend.goods_fujiafei && item.extend.goods_fujiafei.length > 0) {
            item.extend.goods_fujiafei.forEach((fee: any) => {
              if (Number.parseFloat(fee.total) > 0) {
                fujiafeiList[fee.name] = Number.parseFloat(fee.total);
              }
            });
          }
          // 最后备选使用extend.fujiafei
          else if (item.extend && item.extend.fujiafei) {
            item.extend.fujiafei.forEach((fee: any) => {
              if (Number.parseFloat(fee.total) > 0) {
                fujiafeiList[fee.name] = Number.parseFloat(fee.total);
              }
            });
          }

          // 获取规格信息
          const specList: string[] = [];

          // 优先使用goods_guige
          if (item.goods_guige && item.goods_guige.length > 0) {
            item.goods_guige.forEach((guige: any) => {
              specList.push(`1${guige.relation} = ${guige.num} ${guige.unit}`);
            });
          }

          // 计算单价和总价
          const price = item.price || 0;
          const quantity = item.mini_type === '件' ? (item.num || 0) : (item.weight || 0);
          const money = item.total_price || 0;

          // 构建商品项
          goodsList.value.push({
            id: item.id,
            name: item.goods_name || (item.goods ? item.goods.goods_id : '未命名商品'),
            spec: specList,
            fujiafei_list: fujiafeiList,
            quantity: quantity.toString(),
            price: price.toString(),
            money: money.toString(),
            subtotal: money.toString(),
            selected: false,
            unit: item.mini_type || item.unit || '个',
            metadata: item,
          });
        });
      }
    }
    catch (error) {
      console.error('获取买家购物车数据失败', error);
    }
  }
};

// 清空购物车功能
const clearAllItems = async () => {
  // 显示确认对话框
  uni.showModal({
    title: '确认清空',
    content: '确定要清空购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const selectedBuyer = buyerList.value[selectedBuyerIndex.value];

          // 调用deleteCar接口清空购物车，传入空字符串作为order_car_id
          const res = await deleteCar({
            car_id: selectedBuyer.id,
            order_car_id: '',
          });

          if (res.code === 200) {
            // 清空成功，清空本地商品列表
            goodsList.value = [];
            uni.showToast({
              title: '清空成功',
              icon: 'success',
            });
          }
          else {
            uni.showToast({
              title: res.msg || '清空失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          console.error('清空购物车失败', error);
          uni.showToast({
            title: '清空失败',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 生命周期钩子
onMounted(() => {
  uni.$on('updateSelectedBuyer', handleUpdateBuyer);
});

onUnmounted(() => {
  uni.$off('updateSelectedBuyer', handleUpdateBuyer);
});

onLoad((options) => {
  getMaiJiaList(options?.id);
});
</script>
